//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ruoyi.live.user.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.live.app.service.AppService;
import com.ruoyi.live.app.service.CacheService;
import com.ruoyi.live.configuration.SessionInfo;
import com.ruoyi.live.exam.domain.ScoreObjDetail;
import com.ruoyi.live.base.domain.*;
import com.ruoyi.live.base.mapper.*;
import com.ruoyi.live.tool.commons.ICommons;
import com.ruoyi.live.tool.commons.IConvert;
import com.ruoyi.live.tool.utils.Message;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExpertService {
    private static final Logger log = LoggerFactory.getLogger(ExpertService.class);
    @Autowired
    LiveExamMapper examDao;
    @Autowired
    LiveExamUserMapper examUserDao;
    @Autowired
    LiveExamJudgeMapper judgeDao;
    @Autowired
    LiveExamExpertDetailMapper expertDetailDao;
    @Autowired
    CacheService cacheService;
    @Autowired
    LiveTaskUserDetailMapper detailDao;
    @Autowired
    LiveTaskUserMapper taskUserDao;
    @Autowired
    LiveExamExpertMapper expertDao;
    @Autowired
    LiveTaskUserChannelMapper channelDao;
    @Autowired
    LiveBarrageChannelMapper barChannelDao;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    LiveProductItemMapper itemDao;
    @Autowired
    LiveTaskUserChannelReconnectMapper reDao;
    @Autowired
    LiveTaskUserPutMapper putDao;
    @Autowired
    UserMapper userDao;
    @Autowired
    LiveExamObjectiveScoreDetailMapper scoreDetailDao;
    @Autowired
    LiveExamObjectiveScoreMapper liveExamObjectiveScoreMapper;

    public ExpertService() {
    }

    public List<LiveExamJudge> list(Long examId) {
        List<LiveExamJudge> judges = this.judgeDao.selectList((Wrapper)(new QueryWrapper((new LiveExamJudge()).setExamId(examId).setUserJudgeId(SessionInfo.getUserId()))).in("state", new Object[]{1, 2}));
        Iterator var3 = judges.iterator();

        while(var3.hasNext()) {
            LiveExamJudge judge = (LiveExamJudge)var3.next();
            if (1 == judge.getState()) {
                this.judgeDao.updateById(judge.setState(2));
            }
        }

        return judges;
    }

    public List<LiveExamJudge> getJudgeQueue(Long examId) {
        List<LiveExamJudge> judges = this.judgeDao.selectList(new QueryWrapper((new LiveExamJudge()).setExamId(examId).setUserJudgeId(SessionInfo.getUserId()).setState(1)));
        Iterator var3 = judges.iterator();

        while(var3.hasNext()) {
            LiveExamJudge judge = (LiveExamJudge)var3.next();
            this.judgeDao.updateById(judge.setState(2));
        }

        return judges;
    }

    public Message doGetScoreNeed(Long id, Long examUserId) {
        try {
            if (ICommons.isNullOrEmpty(examUserId)) {
                examUserId = this.doUpdateLiveExamJudge(id);
                if (examUserId == null) {
                    return new Message(true, "");
                }
            }

            return new Message(true, JSONArray.of(this.detailDao.getDetails(examUserId)).toString());
        } catch (Exception var4) {
            var4.printStackTrace();
            log.error("获取评审信息失败", var4);
            throw var4;
        }
    }

    public Long doUpdateLiveExamJudge(Long id) {
        LiveExamJudge judge = (LiveExamJudge)this.judgeDao.selectById(id);
        LiveExamUser examUser = (LiveExamUser)this.examUserDao.selectOne(new QueryWrapper((new LiveExamUser()).setCreateUser(judge.getUserPlayerId()).setExamId(judge.getExamId())));
        if (examUser != null) {
            this.judgeDao.updateById((new LiveExamJudge()).setId(id).setExamUserId(examUser.getId()));
            return examUser.getId();
        } else {
            return null;
        }
    }

    public List<LiveScoreStandard> loadShopRules(Integer type, Long examUserId) {
        if (ICommons.isNullOrEmpty(examUserId)) {
            return null;
        } else {
            List<LiveScoreStandard> list = new ArrayList();
            List taskUsers;
            List sources;
            Iterator var6;
            LiveScoreStandard parent;
            LiveScoreStandard c;
            if (type == 1) {
                taskUsers = this.taskUserDao.selectList((Wrapper)(new QueryWrapper((new LiveTaskUser()).setLeuId(examUserId).setTaskType(1))).orderByAsc("task_order"));
                sources = this.cacheService.getStandards(type);
                var6 = sources.iterator();

                while(var6.hasNext()) {
                    parent = (LiveScoreStandard)var6.next();
                    parent.setScore((BigDecimal)null);

                    for(int i = 0; i < taskUsers.size(); ++i) {
                        LiveTaskUser taskUser = (LiveTaskUser)taskUsers.get(i);
                        LiveScoreStandard obj = parent;
                        if (i != 0) {
                            obj = (LiveScoreStandard) JSON.parseObject(JSONObject.toJSONString(parent), LiveScoreStandard.class);
                        }

                        list.add(obj.setProductId(taskUser.getProductId()).setTaskUserId(taskUser.getId()).setProductName(this.cacheService.getProductNameById(taskUser.getProductId())));
                    }
                }
            } else {
                taskUsers = this.taskUserDao.selectList((Wrapper)(new QueryWrapper((new LiveTaskUser()).setLeuId(examUserId))).orderByAsc("task_order"));
                sources = this.cacheService.getStandards(type);
                var6 = sources.iterator();

                label148:
                while(true) {
                    while(true) {
                        if (!var6.hasNext()) {
                            break label148;
                        }

                        parent = (LiveScoreStandard)var6.next();
                        parent.setScore((BigDecimal)null);
                        LiveTaskUser liveTask = null;

                        int i;
                        LiveTaskUser taskUser;
                        for(i = 0; i < taskUsers.size(); ++i) {
                            taskUser = (LiveTaskUser)taskUsers.get(i);
                            if (taskUser.getTaskType() == 2) {
                                liveTask = taskUser;
                                break;
                            }
                        }

                        if (parent.getScoreScope() == 2) {
                            for(i = 0; i < taskUsers.size(); ++i) {
                                taskUser = (LiveTaskUser)taskUsers.get(i);
                                if (taskUser.getTaskType() == 1) {
                                    c = parent;
                                    if (i != 0) {
                                        c = (LiveScoreStandard)JSON.parseObject(JSONObject.toJSONString(parent), LiveScoreStandard.class);
                                    }

                                    list.add(c.setProductId(taskUser.getProductId()).setTaskUserId(taskUser.getId()).setProductName(this.cacheService.getProductNameById(taskUser.getProductId())));
                                }
                            }
                        } else {
                            list.add(parent.setTaskUserId(liveTask.getId()));
                        }
                    }
                }
            }

            taskUsers = this.expertDetailDao.selectList(new QueryWrapper((new LiveExamExpertDetail()).setCreateUser(SessionInfo.getUserId()).setExamUserId(examUserId)));
            HashMap endMap;
            Iterator var18;
            LiveScoreStandard lss;
            if (taskUsers.size() != 0) {
                endMap = new HashMap();
                var6 = taskUsers.iterator();

                while(var6.hasNext()) {
                    LiveExamExpertDetail detail = (LiveExamExpertDetail)var6.next();
                    endMap.put(detail.getStandardId() + "-" + (ICommons.isNullOrEmpty(detail.getProductId()) ? "" : detail.getProductId()), detail);
                }

                var6 = list.iterator();

                while(var6.hasNext()) {
                    parent = (LiveScoreStandard)var6.next();
                    var18 = parent.getStandards().iterator();

                    while(var18.hasNext()) {
                        lss = (LiveScoreStandard)var18.next();
                        LiveExamExpertDetail detail = (LiveExamExpertDetail)endMap.get(lss.getId() + "-" + (ICommons.isNullOrEmpty(parent.getProductId()) ? "" : parent.getProductId()));
                        if (detail == null) {
                            lss.setScore((BigDecimal)null);
                            lss.setScoreState(1);
                        } else {
                            lss.setScore(detail.getScore());
                            lss.setScoreState(detail.getState());
                        }
                    }
                }
            }

            endMap = new HashMap();
            var6 = list.iterator();

            while(var6.hasNext()) {
                parent = (LiveScoreStandard)var6.next();
                if (!ICommons.isNullOrEmpty(parent.getProductId())) {
                    List<LiveScoreStandard> ced = (List)endMap.get(parent.getProductId());
                    if (ced == null) {
                        ced = new ArrayList();
                        endMap.put(parent.getProductId(), ced);
                    }

                    ((List)ced).add(parent);
                }
            }

            List<LiveScoreStandard> result = new ArrayList();
            List<Long> productIds = new ArrayList();
            var18 = list.iterator();

            while(true) {
                while(var18.hasNext()) {
                    lss = (LiveScoreStandard)var18.next();
                    if (!ICommons.isNullOrEmpty(lss.getProductId())) {
                        if (!productIds.contains(lss.getProductId())) {
                            Iterator var23 = ((List)endMap.get(lss.getProductId())).iterator();

                            while(var23.hasNext()) {
                                c = (LiveScoreStandard)var23.next();
                                result.add(c);
                            }
                        }

                        productIds.add(lss.getProductId());
                    } else {
                        result.add(lss);
                    }
                }

                return result;
            }
        }
    }

    public void doEndEmptyJudge(Long id) {
        List<LiveExamExpert> experts = this.expertDao.selectList(new QueryWrapper((new LiveExamExpert()).setJudgeId(id)));
        if (experts.size() == 0) {
            LiveExamJudge judge = (LiveExamJudge)this.judgeDao.selectById(id);
            LiveExamExpert expert = (new LiveExamExpert()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setExamId(judge.getExamId()).setJudgeId(id).setState(3).setStudentId(judge.getUserPlayerId()).setExamUserId(judge.getExamUserId()).setErrState(2).setErrMsg("未做，零分").setScore(new BigDecimal(0));
            this.expertDao.insert(expert);
        } else {
            this.expertDao.updateById((new LiveExamExpert()).setId(((LiveExamExpert)experts.get(0)).getId()).setState(3));
        }

        this.judgeDao.updateById((new LiveExamJudge()).setId(id).setState(3));
    }

    public Message score(Long examId, Long examUserId, Long judgeId) {
        List<LiveExamExpert> experts = this.expertDao.selectList(new QueryWrapper((new LiveExamExpert()).setJudgeId(judgeId)));
        if (experts.size() > 0) {
            return new Message(true, Long.toString(((LiveExamExpert)experts.get(0)).getId()), ((LiveExamExpert)experts.get(0)).getState() + "");
        } else {
            LiveExamUser eu = (LiveExamUser)this.examUserDao.selectById(examUserId);
            LiveExamExpert expert = (new LiveExamExpert()).setCreateTime(System.currentTimeMillis()).setCreateUser(SessionInfo.getUserId()).setExamId(examId).setJudgeId(judgeId).setState(1).setStudentId(eu.getCreateUser()).setExamUserId(examUserId).setErrState(1);
            this.expertDao.insert(expert);
            return new Message(true, Long.toString(expert.getId()), expert.getState() + "");
        }
    }

    public void setScore(LiveExamExpertDetail detail) {
        List<LiveExamExpertDetail> details = this.expertDetailDao.selectList(new QueryWrapper((new LiveExamExpertDetail()).setCreateUser(SessionInfo.getUserId()).setProductId(detail.getProductId()).setExpertId(detail.getExpertId()).setExamUserId(detail.getExamUserId()).setStandardId(detail.getStandardId())));
        if (details.size() == 0) {
            this.expertDetailDao.insert(detail.setState(1).setCreateUser(SessionInfo.getUserId()));
        } else {
            this.expertDetailDao.updateById(((LiveExamExpertDetail)details.get(0)).setState(1).setScore(detail.getScore()));
        }

    }

    public Message getVideoPath(Long id) {
        List<LiveTaskUser> taskUsers = this.taskUserDao.selectList(new QueryWrapper((new LiveTaskUser()).setLeuId(id)));
        if (taskUsers.size() > 0) {
            List<String> productNames = new ArrayList();
            LiveTaskUser liveTask = null;
            Iterator var5 = taskUsers.iterator();

            while(var5.hasNext()) {
                LiveTaskUser ltu = (LiveTaskUser)var5.next();
                if (ltu.getTaskType() == 1) {
                    productNames.add(this.cacheService.getProductNameById(ltu.getProductId()));
                } else if (ltu.getTaskType() == 2) {
                    liveTask = ltu;
                }
            }

            List<LiveTaskUserChannel> channels = this.channelDao.selectList(new QueryWrapper((new LiveTaskUserChannel()).setChannelType(2).setTaskUserId(liveTask.getId())));
            if (channels.size() > 0) {
                LiveTaskUserChannel channel = (LiveTaskUserChannel)channels.get(0);
                channel.setLiveLength(AppService.getDelayTime(channel.getCreateTime(), channel.getEndTime()));

                try {
                    channel.setReconnects(this.reDao.selectList(new QueryWrapper((new LiveTaskUserChannelReconnect()).setTaskChannelId(channel.getId()))));
                    channel.setCostTime(IConvert.long2int((channel.getEndTime() - channel.getCreateTime()) / 1000L));
                } catch (Exception var8) {
                    var8.printStackTrace();
                }

                return new Message(true, JSON.toJSONString(channel), StringUtils.join(productNames, ","));
            } else {
                return new Message(false, "获取视频出错");
            }
        } else {
            return new Message(false, "获取视频出错");
        }
    }

    public List<LiveBarrageChannel> getBarrage(Integer start, Integer end, Long id) {
        List<LiveBarrageChannel> list = null;
        if (end - start == 1) {
            list = this.barChannelDao.selectList((Wrapper)(new QueryWrapper((new LiveBarrageChannel()).setChannelId(id).setTimeIndex(end))).orderByAsc("time_index"));
        } else {
            List<LiveBarrageChannel> problems = this.barChannelDao.selectList((Wrapper)((QueryWrapper)(new QueryWrapper((new LiveBarrageChannel()).setChannelId(id).setType(5))).le("time_index", end)).orderByAsc("time_index"));
            String sql = "select * from live_barrage_channel where channel_id=? and time_index<=? and type!=5 order by time_index asc limit 10";
            list = this.jdbcTemplate.query(sql, new Object[]{id, end}, new BeanPropertyRowMapper(LiveBarrageChannel.class));
            list.addAll(problems);
        }

        Iterator var7 = list.iterator();

        while(var7.hasNext()) {
            LiveBarrageChannel channel = (LiveBarrageChannel)var7.next();
            channel.setContent(this.cacheService.giftBarrageByIdCache(channel.getBarrageId()).getContent());
        }

        return list;
    }

    public List<LiveExamExpertDetail> getScoreData(Long id) {
        return this.expertDetailDao.selectList(new QueryWrapper((new LiveExamExpertDetail()).setExpertId(SessionInfo.getUserId()).setExamUserId(id)));
    }

    public LiveProductItem getProductDetailById(Long id) {
        List<LiveProductItem> items = this.itemDao.selectList(new QueryWrapper((new LiveProductItem()).setProductId(id)));
        return items.size() > 0 ? (LiveProductItem)items.get(0) : null;
    }

    public Boolean hasAllDone(Long examUserId) {
        Long allCount = this.judgeDao.selectCount(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUserId)));
        Long doneCount = this.expertDao.selectCount(new QueryWrapper((new LiveExamExpert()).setExamUserId(examUserId).setState(2)));
        return allCount.equals(doneCount) ? true : false;
    }

    public Boolean doCalculation(List<LiveExamExpertDetail> list, LiveScoreStandard standard, Long productId) {
        Boolean correct = true;
        if (!(new Integer(1)).equals(standard.getScoreType())) {
            correct = ((LiveExamExpertDetail)list.get(list.size() - 1)).getScore().intValue() - ((LiveExamExpertDetail)list.get(0)).getScore().intValue() <= 1;
        } else {
            correct = ((LiveExamExpertDetail)list.get(list.size() - 1)).getScore().compareTo(((LiveExamExpertDetail)list.get(0)).getScore()) == 0;
        }

        UpdateWrapper<LiveExamExpertDetail> updateWrapper = new UpdateWrapper();
        if (!ICommons.isNullOrEmpty(productId)) {
            updateWrapper.eq("product_id", productId);
        }

        ((UpdateWrapper)updateWrapper.eq("standard_id", standard.getId())).set("state", correct ? 2 : 3);
        this.expertDetailDao.update(null, updateWrapper);
        return correct;
    }

    public Boolean isOneStandard(Long baseStandardId, Long baseProductId, LiveScoreStandard baseStandard, LiveExamExpertDetail detail) {
        if (!detail.getStandardId().equals(baseStandardId)) {
            return false;
        } else if (baseStandard.getScoreScope() == 2) {
            return baseProductId.equals(detail.getProductId()) ? true : false;
        } else {
            return true;
        }
    }

    public Message doWorldGameRule(Long examUserId) {
        List<LiveExamExpertDetail> expertDetails = this.expertDetailDao.selectList((Wrapper)((QueryWrapper)((QueryWrapper)(new QueryWrapper((new LiveExamExpertDetail()).setExamUserId(examUserId))).orderByAsc("standard_id")).orderByAsc("product_id")).orderByAsc("score"));
        Boolean correct = true;
        Long baseStandardId = ((LiveExamExpertDetail)expertDetails.get(0)).getStandardId();
        Long baseProductId = ((LiveExamExpertDetail)expertDetails.get(0)).getProductId();
        LiveScoreStandard baseStandard = this.cacheService.getScoreItemById(baseStandardId);
        List<LiveExamExpertDetail> list = new ArrayList();
        Integer editCount = 0;

        for(int i = 0; i <= expertDetails.size(); ++i) {
            LiveExamExpertDetail detail = i < expertDetails.size() ? (LiveExamExpertDetail)expertDetails.get(i) : null;
            if (detail == null || !this.isOneStandard(baseStandardId, baseProductId, baseStandard, detail)) {
                Boolean res = this.doCalculation(list, baseStandard, baseProductId);
                editCount = editCount + (res ? 0 : 1);
                if (correct) {
                    correct = res;
                }

                if (detail != null) {
                    list = new ArrayList();
                    baseStandardId = detail.getStandardId();
                    baseProductId = detail.getProductId();
                    baseStandard = this.cacheService.getScoreItemById(baseStandardId);
                }
            }

            list.add(detail);
        }

        list = null;
        return new Message(correct, "存在" + editCount + "个评分点不符合规则，已标红，请重新评分", "load");
    }

    public Message doEndJudgeZZ(Long id) {
        try {
            LiveExamExpert expert = (LiveExamExpert)this.expertDao.selectById(id);
            if (!ICommons.isNullOrEmpty(expert.getExamUserId())) {
                Integer allCount = this.cacheService.getScoreItemCount();
                Long currentCount = this.expertDetailDao.selectCount(new QueryWrapper((new LiveExamExpertDetail()).setExamUserId(expert.getExamUserId()).setExpertId(expert.getId())));
                String tg = this.cacheService.getParam("SYSTEM_NC");
                if (ICommons.isNullOrEmpty(tg)) {
                    tg = "1";
                }

                if (currentCount < allCount.longValue() && "1".equalsIgnoreCase(tg)) {
                    return new Message(false, "存在未打分的评分项,无法提交");
                }

                String sql = "select ifnull(sum(score),0) score from live_exam_expert_detail where expert_id = ?";
                List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql, new Object[]{id});
                BigDecimal bg = new BigDecimal(0);
                if (list.size() > 0) {
                    bg = new BigDecimal(IConvert.object2string(((Map)list.get(0)).get("score")));
                }

                this.expertDao.updateById((new LiveExamExpert()).setId(id).setState(2).setScore(bg));
                this.judgeDao.updateById((new LiveExamJudge()).setState(3).setId(expert.getJudgeId()));
                this.doFinalScoreZZ(expert.getExamUserId());
            }

            return new Message(true, "评审成功");
        } catch (Exception var9) {
            return new Message(false, "评审提交失败");
        }
    }

    public void doFinalScoreZZ(Long examUserId) {
        if (examUserId != null) {
            List<LiveExamJudge> judges = this.judgeDao.selectList(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUserId)));
            Long count = this.judgeDao.selectCount((Wrapper)(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUserId))).ne("state", 3));
            if (count == 0l) {
                String sql = "select id,score from live_exam_expert where judge_id in (select a.id from live_exam_judge a where a.exam_user_id = ?) order by score";
                List<LiveExamExpert> experts = this.jdbcTemplate.query(sql, new Object[]{examUserId}, new BeanPropertyRowMapper(LiveExamExpert.class));
                BigDecimal sum = new BigDecimal("0");
                Integer expertSize = experts.size();

                for(int i = 0; i < expertSize; ++i) {
                    if (expertSize < 5 || i != 0 && i != expertSize - 1) {
                        sum = sum.add(((LiveExamExpert)experts.get(i)).getScore());
                    }
                }

                LiveExamUser leu = (LiveExamUser)this.examUserDao.selectById(examUserId);
                Integer avg = expertSize >= 5 ? expertSize - 2 : expertSize;
                sum = sum.divide(new BigDecimal(avg), 3, 4);
                if (!ICommons.isNullOrEmpty(leu.getObjScore())) {
                    this.examUserDao.updateById((new LiveExamUser()).setId(examUserId).setExpertScore(sum).setScore(leu.getObjScore().add(sum)));
                } else {
                    this.examUserDao.updateById((new LiveExamUser()).setId(examUserId).setExpertScore(sum));
                }
            }
        }

    }

    public Message doEndJudge(Long id) throws Exception {
        LiveExamExpert expert = (LiveExamExpert)this.expertDao.selectById(id);
        if (ICommons.isNullOrEmpty(expert.getExamUserId())) {
            return new Message(true, "评审成功");
        } else {
            Integer allCount = this.cacheService.getScoreItemCount();
            Long currentCount = this.expertDetailDao.selectCount(new QueryWrapper((new LiveExamExpertDetail()).setExamUserId(expert.getExamUserId()).setExpertId(expert.getId())));
            if (currentCount < allCount.longValue()) {
                return new Message(false, "存在未打分的评分项,无法提交");
            } else {
                this.expertDao.updateById((new LiveExamExpert()).setId(id).setState(2));
                if (!this.hasAllDone(expert.getExamUserId())) {
                    return new Message(false, "wait");
                } else {
                    Message res = this.doWorldGameRule(expert.getExamUserId());
                    if (!res.isSuccess()) {
                        this.expertDao.update(null, (Wrapper)((UpdateWrapper)(new UpdateWrapper()).eq("exam_user_id", expert.getExamUserId())).set("state", 4));
                        return res;
                    } else {
                        List<LiveExamExpert> experts = this.expertDao.selectList((new QueryWrapper((new LiveExamExpert()).setExamUserId(expert.getExamUserId()))).select(new String[]{"id", "judge_id"}));
                        Iterator var7 = experts.iterator();

                        while(var7.hasNext()) {
                            LiveExamExpert exp = (LiveExamExpert)var7.next();
                            this.doScoreExpert(exp.getId(), exp.getJudgeId());
                        }

                        this.doFinalScore(expert.getExamUserId());
                        return new Message(true, "评审成功");
                    }
                }
            }
        }
    }

    public void doScoreExpert(Long expertId, Long judgeId) {
        List<LiveExamExpertDetail> details = this.expertDetailDao.selectList(new QueryWrapper((new LiveExamExpertDetail()).setExpertId(expertId)));
        BigDecimal sum = new BigDecimal("0");
        Iterator var5 = details.iterator();

        while(var5.hasNext()) {
            LiveExamExpertDetail detail = (LiveExamExpertDetail)var5.next();
            LiveScoreStandard standard = this.cacheService.getScoreItemById(detail.getStandardId());
            if (standard.getScoreType() == 1) {
                sum = sum.add(detail.getScore().intValue() == 3 ? standard.getStandardValue() : new BigDecimal("0"));
            } else if (standard.getScoreType() == 2) {
                sum = sum.add(standard.getStandardValue().multiply(detail.getScore()).divide(new BigDecimal("3"), 5, RoundingMode.UP));
            } else if (standard.getScoreType() == 3) {
                sum = sum.add((BigDecimal)standard.getScores().get(detail.getScore().intValue()));
            }
        }

        this.expertDao.updateById((new LiveExamExpert()).setId(expertId).setState(3).setScore(sum));
        this.judgeDao.updateById((new LiveExamJudge()).setState(3).setId(judgeId));
    }

    public void doFinalScore(Long examUserId) {
        String useWorld = this.cacheService.getParam("USE_WORLD_RULE");
        Integer paramInt = 2;
        if (Objects.equals("1", useWorld)) {
            paramInt = 3;
        }

        if (examUserId != null) {
            List<LiveExamJudge> judges = this.judgeDao.selectList(new QueryWrapper((new LiveExamJudge()).setExamUserId(examUserId)));
            if (judges.size() > 0) {
                String sql = "select count(1) count,sum(state) state,avg(score) score from live_exam_expert where exam_user_id = ?";
                List<Map<String, Object>> res = this.jdbcTemplate.queryForList(sql, new Object[]{examUserId});
                if (res.size() > 0) {
                    Integer count = IConvert.object2int(((Map)res.get(0)).get("count"));
                    Integer state = IConvert.object2int(((Map)res.get(0)).get("state"));
                    Double score = IConvert.object2double(((Map)res.get(0)).get("score"));
                    if (count * paramInt == state && judges.size() == count) {
                        LiveExamUser leu = (LiveExamUser)this.examUserDao.selectById(examUserId);
                        if (!ICommons.isNullOrEmpty(leu.getObjScore())) {
                            Double finalScore = leu.getObjScore().doubleValue() + score;
                            this.examUserDao.updateById((new LiveExamUser()).setId(examUserId).setExpertScore(new BigDecimal(score)).setScore(new BigDecimal(finalScore)));
                        } else {
                            this.examUserDao.updateById((new LiveExamUser()).setId(examUserId).setExpertScore(new BigDecimal(score)));
                        }
                    }
                }
            }
        }

    }

    public List<LiveExamJudge> listStudent(Long examId) {
        Long classId = ((User)this.userDao.selectById(SessionInfo.getUserId())).getUserSchool();
        String sql = "select a.user_login_name,b.*,c.score,c.id expert_id,c.err_state err from user a left join live_exam_judge b on a.id = b.user_player_id and b.user_judge_id = ? and b.exam_id = ?  left join live_exam_expert c on b.id = c.judge_id  where a.class_id = ?";
        return this.jdbcTemplate.query(sql, new Object[]{SessionInfo.getUserId(), examId, classId}, new BeanPropertyRowMapper(LiveExamJudge.class));
    }

    public void checkScoreId(Long id) {
        LiveExamExpert expert = (LiveExamExpert)this.expertDao.selectById(id);
        this.expertDao.updateById(expert.setState(1));
        this.judgeDao.updateById((new LiveExamJudge()).setId(expert.getJudgeId()).setState(2));
    }

    public Map<String, List<Integer>> getTimeIndex(Long examUserId) {
        Map<String, List<Integer>> res = new HashMap();
        LiveTaskUser taskUser = (LiveTaskUser)this.taskUserDao.selectOne((new QueryWrapper((new LiveTaskUser()).setLeuId(examUserId).setTaskType(2))).select(new String[]{"id"}));
        LiveTaskUserChannel channel = (LiveTaskUserChannel)this.channelDao.selectOne((new QueryWrapper((new LiveTaskUserChannel()).setChannelType(2).setTaskUserId(taskUser.getId()))).select(new String[]{"id"}));
        List<LiveTaskUserPut> puts = this.putDao.selectList((new QueryWrapper((new LiveTaskUserPut()).setChannelId(channel.getId()))).select(new String[]{"time_index"}));
        res.put("product", puts.stream().map((e) -> {
            return e.getTimeIndex();
        }).collect(Collectors.toList()));
        String sql = "select c.product_id id, group_concat(c.time_index) timeindex from (select a.time_index,b.product_id from live_barrage_channel a left join live_barrage b on a.barrage_id = b.id where a.type = 5 and a.channel_id = ?  order by a.time_index asc) c group by product_id";
        List<Map<String, Object>> list = this.jdbcTemplate.queryForList(sql, new Object[]{channel.getId()});
        Iterator var8 = list.iterator();

        while(var8.hasNext()) {
            Map<String, Object> map = (Map)var8.next();
            List<Integer> indexs = new ArrayList();
            String[] inds = String.valueOf(map.get("timeindex")).split(",");

            for(int i = 0; i < inds.length; ++i) {
                indexs.add(IConvert.string2int(inds[i]));
            }

            res.put(String.valueOf(map.get("id")), indexs);
        }

        return res;
    }

    public Message getExpertState(Long id) {
        LiveExamExpert expert = (LiveExamExpert)this.expertDao.selectById(id);
        return new Message(true, expert.getState() + "");
    }

    public Message getScoreState(Long examId) {
        User expert = (User)this.userDao.selectById(SessionInfo.getUserId());
        Long count = this.userDao.selectCount(new QueryWrapper((new User()).setUserType(3).setClassId(expert.getUserSchool())));
        Long judgeCount = this.judgeDao.selectCount(new QueryWrapper((new LiveExamJudge()).setExamId(examId).setState(3).setUserJudgeId(expert.getId())));
        if (count == 0l) {
            return new Message(true, "");
        } else {
            return count.equals(judgeCount) ? new Message(true, "") : new Message(false, "");
        }
    }

    public List<LiveExamJudge> scoreOne(Long examId) {
        PageHelper.startPage(1, 1);
        List<LiveExamJudge> judges = this.judgeDao.selectList((Wrapper)(new QueryWrapper((new LiveExamJudge()).setExamId(examId).setUserJudgeId(SessionInfo.getUserId()).setState(3))).orderByDesc("id"));
        return judges;
    }

    public List<LiveScoreStandard> loadAllRules(Long examUserId) {
        List<LiveScoreStandard> shops = this.loadShopRules(1, examUserId);
        List<LiveScoreStandard> products = this.loadShopRules(2, examUserId);
        shops.addAll(products);
        Iterator var4 = shops.iterator();

        while(var4.hasNext()) {
            LiveScoreStandard standard = (LiveScoreStandard)var4.next();
            Iterator var6 = standard.getStandards().iterator();

            while(var6.hasNext()) {
                LiveScoreStandard child = (LiveScoreStandard)var6.next();
                LiveScoreStandard realStandard = this.cacheService.getScoreItemById(child.getId());
                if (child.getScoreType() == 1) {
                    child.setRealScore(child.getScore().intValue() == 3 ? realStandard.getStandardValue() : new BigDecimal("0"));
                } else if (child.getScoreType() == 2) {
                    child.setRealScore(child.getScore().multiply(realStandard.getStandardValue()).divide(new BigDecimal("3"), 5, RoundingMode.UP));
                } else if (child.getScoreType() == 3) {
                    child.setRealScore((BigDecimal)realStandard.getScores().get(child.getScore().intValue()));
                }
            }
        }

        return shops;
    }

    public List<ScoreObjDetail> getScoreDetail(Long examUserId) {
        LiveExamObjectiveScore liveExamObjectiveScore = (LiveExamObjectiveScore)this.liveExamObjectiveScoreMapper.selectOne(new QueryWrapper((new LiveExamObjectiveScore()).setExamUserId(examUserId)));
        Long id = liveExamObjectiveScore.getId();
        List<LiveExamObjectiveScoreDetail> list = this.scoreDetailDao.selectList(new QueryWrapper((new LiveExamObjectiveScoreDetail()).setScoreId(id)));
        Map<Long, ScoreObjDetail> res = new HashMap();

        LiveExamObjectiveScoreDetail detail;
        Long productId;
        ScoreObjDetail sod;
        for(Iterator var6 = list.iterator(); var6.hasNext(); sod.getList().add(detail)) {
            detail = (LiveExamObjectiveScoreDetail)var6.next();
            productId = detail.getProductId() == null ? 0L : detail.getProductId();
            sod = (ScoreObjDetail)res.get(productId);
            if (sod == null) {
                String productName = "其他";
                if (!productId.equals(0L)) {
                    productName = this.cacheService.getProductNameById(productId);
                }

                sod = (new ScoreObjDetail()).setProductId(productId).setProductName(productName);
                res.put(productId, sod);
            }
        }

        List<ScoreObjDetail> details = new ArrayList();
        Iterator var12 = res.keySet().iterator();

        while(var12.hasNext()) {
            productId = (Long)var12.next();
            details.add(res.get(productId));
        }

        return details;
    }

    public void doResetExpertState(Long examUserId) throws Exception {
        if (examUserId == null) {
            throw new Exception("examUserId不能为null");
        } else {
            this.judgeDao.update((new LiveExamJudge()).setState(2), new QueryWrapper((new LiveExamJudge()).setExamUserId(examUserId)));
            this.expertDao.update((new LiveExamExpert()).setState(1), new QueryWrapper((new LiveExamExpert()).setExamUserId(examUserId)));
            this.expertDetailDao.update((new LiveExamExpertDetail()).setState(1), new QueryWrapper((new LiveExamExpertDetail()).setExamUserId(examUserId)));
        }
    }
}
